package com.yang.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.demo.constants.MailConstants;
import com.yang.demo.entity.Employee;
import com.yang.demo.entity.MailLog;
import com.yang.demo.entity.RespBean;
import com.yang.demo.entity.RespPageBean;
import com.yang.demo.mapper.EmployeeMapper;
import com.yang.demo.mapper.MailLogMapper;
import com.yang.demo.service.IEmployeeService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaoyang
 * @since 2022-07-09
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;


    /**
     * 获取所有员工的工资账套(分页查询)
     *
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer size) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> employeesByPage = employeeMapper.getEmployeeWithSalary(page);
        RespPageBean respPageBean = new RespPageBean(employeesByPage.getTotal(), employeesByPage.getRecords());
        return respPageBean;
    }

    /**
     * 分页查询员工
     *
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public RespPageBean getEmployeesByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {

        //开启分页
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> employeesByPage = employeeMapper.getEmployeesByPage(page, employee, beginDateScope);
        RespPageBean respPageBean = new RespPageBean(employeesByPage.getTotal(), employeesByPage.getRecords());

        return respPageBean;
    }

    /**
     * 获取最大的工号id
     *
     * @return
     */
    @Override
    public RespBean getMaxWorkId() {
        //查询最大的工号,用map存储
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        //通过key获取最大工号的值转成Integer类型再加1转成然后再转成String返回
        return RespBean.success(String.format("%08d", Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1));
    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @Override
    public RespBean addWork(Employee employee) {
        //处理合同期限,保留两位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        //计算两个日期相差多少天数
        long days = beginContract.until(endContract, ChronoUnit.DAYS); //第二个参数计算单位
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days / 365.00)));
        if (days < 0) {
            return RespBean.error("添加失败,离职日期不得早于入职日期!");
        } else if (1 == employeeMapper.insert(employee)) {
            //获取刚添加的用户,发送消息
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);
            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(employee.getId());
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setStatus(0);
            mailLog.setCount(0);
            mailLog.setTryTime(LocalDate.now().atStartOfDay().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            //消息落户
            mailLogMapper.insert(mailLog);
            //发送消息
            rabbitTemplate.convertAndSend("MailConstants.MAIL_EXCHANGE_NAME", MailConstants.MAIL_ROUTING_KEY_NAME, emp, new CorrelationData(msgId));
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败!");
    }

    /**
     * 更新员工(考虑合同期限)
     *
     * @param employee
     * @return
     */
    @Override
    public RespBean updateWorker(Employee employee) {
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        if (!beginContract.equals(employeeMapper.selectById(employee.getId()).getBeginContract())) {
            return RespBean.error("合同时间不能修改!");
        } else if (!endContract.equals(employeeMapper.selectById(employee.getId()).getEndContract())) {
            return RespBean.error("合同时间不能修改!");
        } else {
            employeeMapper.updateById(employee);
            return RespBean.success("修改成功");
        }
    }

    /**
     * 导出员工数据
     *
     * @param id
     */
    @Override
    public List<Employee> exportEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

}
